# 说明:demo都是百度翻译开放平台下载的代码稍微修改的

import requests
import random
from hashlib import md5

# 请修改成为自己的appid和appkey，如果没有，请搜索：百度翻译开放平台自己注册，接口是免费的
# http://api.fanyi.baidu.com/api/trans/product/desktop
appid=''
appkey=''
endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


def query(q,from_lang,to_lang):
    salt=random.randint(32768, 65536)
    sign=make_md5(appid+q+str(salt)+appkey)
    # Build request
    headers={'Content-Type': 'application/x-www-form-urlencoded'}
    payload={'appid': appid, 'q': q, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r=requests.post(url, params=payload, headers=headers)
    result=r.json()

    # print(result['trans_result'])
    ''' 
    list 
    [
        {
            "src": "Hello World! This is 1st paragraph.",
            "dst": "你好，世界！这是第一段。"
        },
        {
            "src": "This is 2nd paragraph.",
            "dst": "这是第二段。"
        }
    ]
    '''
    return result['trans_result']

# ql,查询的单词list，默认是英语翻译成中文，如有其他需要，自己设置以下就好了
def queryList(ql,from_lang='en',to_lang='zh'):
    q = ''
    for w in  ql:
        q += (w + '\n')
    # print(query)
    return query(q,from_lang,to_lang)


# 单元测试
if __name__ == '__main__':
    # q='Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
    # query(q)
    list1 = ['Hello World! This is 1st paragraph.','This is 2nd paragraph.']
    print(queryList(list1),'en','zh')
